package cn.edu.sjtu.gateway.util;

import cn.edu.sjtu.gateway.constant.JWTConstant;
import cn.edu.sjtu.gateway.model.User;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.JWTVerifier;

import java.util.Date;

public class JWTUtil {

    private static final String issuer = "INDUSTRY_GATEWAY";
    private static final Algorithm algorithm = Algorithm.HMAC256(JWTConstant.SECRET_KEY);

    public static String encode(User user) {
        return JWT.create()
                .withIssuer(issuer)
                .withExpiresAt(new Date(System.currentTimeMillis() + JWTConstant.VALIDITY_PERIOD))
                .withAudience(user.getUserId())
                .withClaim("username", user.getUsername())
                .withClaim("role", user.getRole())
                .withClaim("phone", user.getPhone())
                .sign(algorithm);
    }

    public static String decodeUserId(String token) {
        return JWT.decode(token).getAudience().get(0);
    }

    public static Integer decodeRole(String token) {
        return JWT.decode(token).getClaim("role").asInt();
    }

    public static String decodeUsername(String token) {
        return JWT.decode(token).getClaim("username").asString();
    }

    public static String decodePhone(String token) {
        return JWT.decode(token).getClaim("phone").asString();
    }

    public static boolean verify(String token) {
        JWTVerifier jwtVerifier = JWT.require(algorithm).withIssuer(issuer).build();
        try {
            jwtVerifier.verify(token);
            return true;
        } catch (JWTVerificationException e) {
            return false;
        }
    }

}
